<template>
  <!-- BusinessCard 单位名片 -->
  <PageContainer v-model:enter-options="enterOptions">
    <view class="container">
      <Header title="单位主页" />
      <Box :content-p-top="30" :warp-m-bottom="0">
        <ElegantDemeanour v-model="imgList" :card-type="ApplyTypeEnum.UNIT" />
        <CuttingLine background-color="transparent" :margin-bottom="0" />
        <!-- 单位信息 -->
        <view class="unit-info">
          <view class="unit-info--logo">
            <TImage :src="cardDetail?.logo" width="115rpx" height="115rpx" error-img-type="unit" />
          </view>
          <view class="unit-info--text">
            <view class="unit-name text-overflow-1">{{ cardDetail?.name }}</view>
            <view
              class="unit-address"
              v-if="cardDetail?.address"
              @click="openLocation(cardDetail?.address)"
            >
              <view class="ali-icon">&#xe60c;</view>
              <text class="text-overflow-1">{{ parseAddress(cardDetail?.address).address }}</text>
            </view>
          </view>
        </view>
        <CuttingLine background-color="transparent" :margin-bottom="0" />
        <!-- 行业列表 -->
        <template v-if="cardDetail?.mainBusinessList && cardDetail.mainBusinessList.length">
          <view class="industry-tag">
            <template v-for="(v, i) in cardDetail.mainBusinessList" :key="i">
              <view class="industry-tag--item">{{ v }}</view>
            </template>
          </view>
        </template>
        <SourceView :org-tenant-name="cardDetail?.orgTenantName" :info="sourceInfo" />
        <CuttingLine :margin-top="cardDetail?.orgTenantName ? 20 : 0" />
        <BrowseInfo
          :info="cardDetail?.browseInfo"
          :card-type="ApplyTypeEnum.UNIT"
          :id="id"
          :card-id="cardDetail?.id"
        >
          <view
            v-if="cardDetail?.officeTel"
            class="show-officeTel"
            @click="makePhoneCall(cardDetail?.officeTel)"
          >
            <view class="officeTel-icon">
              <image
                class="icon-img"
                src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/card/icon-5.png"
                mode="scaleToFill"
              />
            </view>
            <text>电话</text>
          </view>
        </BrowseInfo>
      </Box>
      <Box
        v-if="cardDetail?.leadingMemberVoList?.length"
        title="成员"
        :content-p-top="0"
        :warp-m-bottom="0"
      >
        <MemberList
          :model-value="cardDetail?.leadingMemberVoList"
          :is-to-details="!isControlCardIn"
        />
      </Box>
      <Box v-if="cardDetail?.honorList?.length" title="社会荣誉/职务" :warpMBottom="0">
        <Honor :icon-type="2" :list="cardDetail.honorList" background="#F9F9F9" />
      </Box>
      <Box
        title="简介"
        v-if="
          imgList.length || videoInfo.videoUrl || cardDetail?.memberDetails || cardDetail?.document
        "
      >
        <VideoPlay v-if="videoInfo.videoUrl" v-model="videoInfo" />
        <template v-if="cardDetail?.document">
          <CuttingLine background-color="transparent" :margin-bottom="0" />
          <Preview :doc-list="cardDetail?.document" :file-name="cardDetail.documentName" />
        </template>
        <template v-if="cardDetail?.memberDetails">
          <CuttingLine background-color="transparent" :margin-bottom="0" />
          <Introduction v-model="cardDetail.memberDetails" />
        </template>
      </Box>
      <FloatingButton
        v-if="enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE"
        :card-type="ApplyTypeEnum.UNIT"
        :id="cardDetail?.memberLeadingId"
        :is-control-card-in="isControlCardIn"
      />
      <TButtonGroup
        v-if="cardDetail && enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE"
      >
        <TButton
          v-if="cardEditButton"
          class="gutter-btn"
          :text="cardEditButton.text"
          :icon="cardEditButton.icon"
          :custom-class="cardEditButton.customClass"
          @click="cardEditButton?.clickFn"
        />
        <TButton
          class="gutter-btn"
          :text="cardShareButton.text"
          :icon="cardShareButton.icon"
          :open-type="cardShareButton?.openType"
          :custom-class="cardShareButton.customClass"
          @click="showSharePopup = true"
        />
      </TButtonGroup>
    </view>
  </PageContainer>
  <CustomShare
    v-if="cardDetail && enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE"
    v-model:visible="showSharePopup"
    @register="handleCustomShareRegister"
  />
</template>

<script lang="ts" setup>
  /**  BusinessCard  单位名片 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import { orgBusinessCardCompany } from '@/api/card';
  import { type UnitCardDetailsResult } from '@/api/card/types';
  import Header from '@/components/Header/index.vue';
  import { isLogin } from '@/utils/is';
  import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
  import { ref, unref } from 'vue';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { storeToRefs } from 'pinia';
  import { navigateTo, onLoad } from '@/router';
  import Box from '../components/box/index.vue';
  import ElegantDemeanour from '../components/elegantDemeanour/index.vue';
  import { ApplyTypeEnum } from '@/enums/membershipEnum';
  import BrowseInfo from '../components/browseInfo/index.vue';
  import CuttingLine from '../components/cuttingLine/index.vue';
  import Honor from '../components/honor/index.vue';
  import VideoPlay from '@/components/VideoPlay/index.vue';
  import Introduction from '../components/introduction/index.vue';
  import Preview from '../components/uploadDocument/preview.vue';
  import FloatingButton from '../components/floatingButton/index.vue';
  import TImage from '@/components/TImage/index.vue';
  import { useLocation } from '@/hooks/core/useLocation';
  import MemberList from '../editBusinessCard/components/memberList.vue';
  import SourceView from '../components/sourceView/index.vue';
  import { type MemberCardPriceResult } from '@/api/member/types';
  import { memberCardPrice } from '@/api/member';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { type BtnResult } from '@/components/TButtonGroup/types';
  import { useAppShare } from '@/hooks/core/useAppShare';
  import { SceneValuesEnum } from '@/enums/sceneValuesEnum';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { addAppShareLog } from '@/api';
  import { createMiniCode } from '@/utils/dynamicConfig';
  import { getBusinessCardPosterData } from '../components/createPosterJson';

  const { setWxSharePath, setWxShareTimelineQuery, createShareQuery } = useAppShare();

  const enterOptions = ref<UniApp.GetLaunchOptionsSyncOptions>();

  const cardShareButton = ref<BtnResult>({
    text: '分享',
    icon: '\ue8b0',
    customClass: 'cardBtn',
  });
  const cardEditButton = ref<BtnResult>();

  const id = ref();
  const useUser = useUserStoreWithOut();
  const { cocInfo } = storeToRefs(useUser);
  const cardDetail = ref<UnitCardDetailsResult>();

  const { parseAddress, openLocation } = useLocation();

  const showSharePopup = ref(false);
  const [
    customShareRegister,
    {
      setWxShareOptions,
      setShareLogId,
      setPosterDrawData,
      setShareTimelineContent,
      setInternalLinkOptions,
    },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      timeline: true,
      copyLink: true,
      insertOffiaccount: true,
    },
  });

  async function handleCustomShareRegister(e: any) {
    customShareRegister(e);
    const query = { id: id.value as number };
    const routeQuery = createShareQuery(query);

    const res = await addAppShareLog({
      path: 'businessCard',
      query: JSON.stringify(routeQuery),
    });

    setInternalLinkOptions({
      name: 'businessCard',
      options: query,
    });

    setShareLogId(res.id);

    const path = setWxSharePath({
      name: 'businessCard',
      options: query,
    });

    const codeImg = await createMiniCode({ shareLogId: res.id });

    setWxShareOptions([
      {
        title: cardDetail.value?.name,
        path,
        imageUrl: cardDetail.value?.share,
      },
    ]);

    setShareTimelineContent({
      query: setWxShareTimelineQuery(query),
      title: cardDetail.value?.name,
      imageUrl: cardDetail.value?.logo,
    });

    await setPosterDrawData(
      getBusinessCardPosterData(
        { title: cardDetail.value?.name!, cardImg: cardDetail.value?.share! },
        codeImg,
      ),
    );
  }

  /** 单位风采数据 */
  const imgList = ref<string[]>([]);
  /** 视频数据 */
  const videoInfo = ref({
    videoUrl: '',
    coverUrl: '',
  });

  const docInfo = ref({
    docFileUrl: '',
    title: '',
  });

  function __init() {
    orgBusinessCardCompany(id.value).then((r) => {
      if (r) {
        cardDetail.value = r;
        getSourceContent(r.tenantId);
        imgList.value = r.imgList;
        videoInfo.value.videoUrl = r.video || '';
        videoInfo.value.coverUrl = r.videoCover || '';
        docInfo.value.title = r.documentName || '';
        docInfo.value.docFileUrl = r.document || '';
        if (r.isUpdate)
          cardEditButton.value = {
            text: '编辑',
            icon: '\ue8ac',
            customClass: 'cardBlackBtn',
            clickFn: () => {
              toEdit();
            },
          };
      }
    });
  }

  const sourceInfo = ref<MemberCardPriceResult>();
  function getSourceContent(tenantId: number) {
    memberCardPrice(tenantId).then((r) => {
      sourceInfo.value = r;
    });
  }

  const isControlCardIn = ref<boolean>();
  onLoad<'BusinessCard'>((op) => {
    isControlCardIn.value = op.isControlCardIn;
    if (op.id) {
      id.value = op.id;
      __init();
    } else {
      isLogin(() => {
        id.value = cocInfo.value.orgCompanyId;
        __init();
      }, true);
    }
  });

  function toEdit() {
    cardDetail.value &&
      navigateTo({
        name: 'editBusinessCard',
        options: { id: unref(id), callback: __init },
      });
  }

  /** 拨打电话 */
  function makePhoneCall(phoneNumber?: string) {
    phoneNumber && uni.makePhoneCall({ phoneNumber });
  }

  onShareAppMessage(() => ({}));

  onShareTimeline(() => ({}));
</script>

<style lang="scss" scoped>
  .unit-info {
    display: flex;
    &--logo {
      width: 115rpx;
      flex-shrink: 0;
      overflow: hidden;
      margin-right: 20rpx;
    }
    &--text {
      color: #767676;
      font-size: 24rpx;
      flex: 1;
      display: flex;
      flex-direction: column;
      .unit-name {
        color: #333;
        font-size: 35rpx;
        margin-bottom: 10rpx;
        font-weight: bolder;
      }
      .unit-address {
        display: flex;
        align-items: center;
        .ali-icon {
          font-size: 27rpx;
          color: #767676;
          margin-right: 10rpx;
        }
      }
    }
  }

  .industry-tag {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    &--item {
      height: 38rpx;
      padding: 0 15rpx;
      color: #a88643;
      border: 1px solid #a88643;
      border-radius: 98rpx;
      margin-right: 20rpx;
      font-size: 24rpx;
      line-height: 38rpx;
      white-space: nowrap;
      margin-bottom: 20rpx;
    }
  }

  .show-officeTel {
    height: inherit;
    color: #333;
    font-size: 24rpx;
    display: flex;
    align-items: center;
    .officeTel-icon {
      width: 48rpx;
      height: 48rpx;
      border-radius: 50%;
      background-color: #f5f5f5;
      margin-right: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      .icon-img {
        width: 25rpx;
        height: 25rpx;
      }
    }
  }

  .member-list {
    display: flex;
    height: 115rpx;
    margin: 0 -30rpx;
    width: 100vw;
  }
</style>
